package com.itheima.nio.tomcat.parse;

import com.itheima.nio.tomcat.anno.WebServlet;
import com.itheima.nio.tomcat.exception.IsNotImplementsHttpServletException;
import com.itheima.nio.tomcat.exception.NotHasWebServletAnnotation;
import com.itheima.nio.tomcat.inter.HttpServlet;
import com.itheima.nio.tomcat.inter.ParseServletConfig;
import com.itheima.nio.tomcat.inter.ServletConcurrentHashMap;

import java.io.File;
import java.lang.annotation.Annotation;

public class AnnoParseServletConfig implements ParseServletConfig {

    public static final String SERVLET_PATH = "itheima-nio-tomcat-1\\src\\com\\itheima\\nio\\tomcat\\servlet";
    public static final String SERVLET_PACKAGE_NAME = "com.itheima.nio.tomcat.servlet.";
    @Override
    public void parse() {
        File file = new File(SERVLET_PATH);
        File[] servletFiles = file.listFiles();
        for (File servletFile : servletFiles){
            String servletFileName = servletFile.getName().replace(".java", "");
            String servletFullClassName = SERVLET_PACKAGE_NAME + servletFileName;
            try {
                Class servletClass = Class.forName(servletFullClassName);
                Class[] servletClassInterfaces = servletClass.getInterfaces();
                boolean flag = false;
                for (Class servletClas : servletClassInterfaces){
                    if (servletClas == HttpServlet.class){
                        flag = true;
                        break;
                    }
                }
                if (flag){
                    HttpServlet httpServlet = (HttpServlet) servletClass.newInstance();
                    WebServlet servletClassAnnotation = (WebServlet)servletClass.getAnnotation(WebServlet.class);
                    if (servletClassAnnotation != null){
                        String urlPatterns = servletClassAnnotation.urlPatterns();
                        ServletConcurrentHashMap.concurrentHashMap.put(urlPatterns, httpServlet);
                    } else {
                        try{
                            throw new NotHasWebServletAnnotation(servletClass.getName() + "not has WebSwevlet Annotation");
                        } catch (NotHasWebServletAnnotation e){
                            e.printStackTrace();
                        }
                    }

                } else {
                    try{
                        throw new IsNotImplementsHttpServletException(servletClass.getName() + "is not implements HttpServlet interface");
                    } catch (IsNotImplementsHttpServletException e){
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
